﻿using System;
using System.Data;
using System.Web.UI.WebControls;

public partial class mrefunds : System.Web.UI.Page
{
    private readonly string mCurrentModule = Credits.Module.ID;
    private readonly string mPageName = "Carte de credit";
    private string appPath = string.Empty;
    public DateTime fTranzactionDate = new DateTime();
    public decimal fTranzactionAmount = 0;
    #region principal
    private decimal principalOriginalSummary = 0;
    private decimal principalPaidSummary = 0;
    private decimal principalWaivedSummary = 0;
    private decimal principalWrittenOffSummary = 0;
    private decimal principalOutstandingSummary = 0;
    private decimal principalOverDueSummary = 0;
    #endregion
    #region interest
    private decimal interestOriginalSummary = 0;
    private decimal interestPaidSummary = 0;
    private decimal interestWaivedSummary = 0;
    private decimal interestWrittenOffSummary = 0;
    private decimal interestOutstandingSummary = 0;
    private decimal interestOverDueSummary = 0;
    #endregion
    #region Fees
    private decimal feesOriginalSummary = 0;
    private decimal feesPaidSummary = 0;
    private decimal feesWaivedSummary = 0;
    private decimal feesWrittenOffSummary = 0;
    private decimal feesOutstandingSummary = 0;
    private decimal feesOverDueSummary = 0;
    #endregion
    #region Penalties
    private decimal penaltiesOriginalSummary = 0;
    private decimal penaltiesPaidSummary = 0;
    private decimal penaltiesWaivedSummary = 0;
    private decimal penaltiesWrittenOffSummary = 0;
    private decimal penaltiesOutstandingSummary = 0;
    private decimal penaltiesOverDueSummary = 0;
    #endregion
    #region Total
    private decimal totalOriginalSummary = 0;
    private decimal totalPaidSummary = 0;
    private decimal totalWaivedSummary = 0;
    private decimal totalWrittenOffSummary = 0;
    private decimal totalOutstandingSummary = 0;
    private decimal totalOverDueSummary = 0;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            appPath = Utils.GetApplicationPath(Request);
            Utils.GetMaster(this).PerformPreloadActions(mCurrentModule, mPageName);

            bool allowHere = Utils.PermissionAllowed(mCurrentModule, Credits.Domains.ManageLoans.Name, Constants.Constants.Classifiers.Permissions_View);
            if (allowHere)
            {
                transactionDateCalendarExtender.Format = Constants.Constants.ISODateBackwardDotsFormat;

                if (!IsPostBack)
                {
                    int loanID = 0;
                    int.TryParse(Request["loanID"], out loanID);

                    FillStartUP(loanID);

                    FillAccountDetail(loanID);
                    FillPreviewForm(loanID);
                    FillRepaymentSchedule(loanID);

                    FillTransaction(loanID);
                    FillLoanDocuments(loanID);
                }
            }
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    private void FillTransaction(int loanID)
    {
        try
        {
            exportTransactionHyperLinkID.NavigateUrl = string.Format("MRefundsPrint.aspx?loanID=" + loanID);
            Credits.DataObjects.LoanObject loanInfo = Utils.ModuleCredits().GetLoanObjectByID(loanID);
            if (loanInfo != null)
            {
                string balanceValue = loanInfo.ContractAmount.ToString();
                decimal.TryParse(balanceValue, out fTranzactionAmount);

                fTranzactionDate = loanInfo.ContractDate;
            }

            DataTable tranzactionDT = Utils.ModuleCredits().GetTranzactionsLoanOrderDT(loanID);

            decimal currencyChange = loanInfo.CurrencyChangeRate;
            if (currencyChange > 0)
            {
                for (int index = 0; index < tranzactionDT.Rows.Count; index++)
                {
                    DateTime payDate = (DateTime)tranzactionDT.Rows[index]["TranzactionDate"];
                    if (payDate > DateTime.Now.Date)
                    {
                        payDate = DateTime.Now.Date;
                    }

                    decimal realChangeRate = Utils.ModuleCredits().GetCurrencyRateByDate(payDate, loanInfo.CurrencyID);
                    if (realChangeRate > 0)
                    {
                        tranzactionDT.Rows[index]["Rate"] = realChangeRate;
                    }
                }
            }

            tranzactionDT.AcceptChanges();
            tranzactionGridView.DataSource = tranzactionDT;
            tranzactionGridView.DataBind();

        }
        catch (Exception ex)
        {
            //todo
        }
    }

    private void FillLoanDocuments(int loanID)
    {
        LoanRepaymentControl.Show();
    }

    private void FillRepaymentSchedule(int loanID)
    {
        if (loanID != 0)
        {
            DataTable ordersDT = Utils.ModuleCredits().GetRefundsLoanOrderDT1(loanID);
            refundGridView.DataSource = ordersDT;
            refundGridView.DataBind();
            if (ordersDT != null && ordersDT.Rows.Count > 0)
            {
                int footerID = ordersDT.Rows.Count - 1;
                decimal.TryParse(ordersDT.Rows[footerID]["principalDueID"].ToString(), out principalOriginalSummary);
                decimal.TryParse(ordersDT.Rows[footerID]["mainPays"].ToString(), out principalPaidSummary);
                principalOutstandingSummary = principalOriginalSummary - principalPaidSummary;

                decimal.TryParse(ordersDT.Rows[footerID]["interestID"].ToString(), out interestOriginalSummary);
                decimal.TryParse(ordersDT.Rows[footerID]["profitPays"].ToString(), out interestPaidSummary);
                interestOutstandingSummary = interestOriginalSummary - interestPaidSummary;

                //decimal.TryParse(ordersDT.Rows[footerID][""].ToString(), out feesOriginalSummary);
                decimal.TryParse(ordersDT.Rows[footerID]["feesID"].ToString(), out feesPaidSummary);
                feesOutstandingSummary = feesOriginalSummary - feesPaidSummary;

                decimal.TryParse(ordersDT.Rows[footerID]["penaltiesID"].ToString(), out penaltiesPaidSummary);
                penaltiesOutstandingSummary = penaltiesPaidSummary;
            }
            #region principal
            fSetLabelText(principalOriginalLabel, principalOriginalSummary);
            fSetLabelText(principalPaidLabel, principalPaidSummary);
            fSetLabelText(principalWaivedLabel, principalWaivedSummary);
            fSetLabelText(principalWrittenOffLabel, principalWrittenOffSummary);
            fSetLabelText(principalOutstandingLabel, principalOutstandingSummary);
            fSetLabelText(principalOverDueLabel, principalOverDueSummary);
            #endregion
            #region interest
            fSetLabelText(interestOriginalLabel, interestOriginalSummary);
            fSetLabelText(interestPaidLabel, interestPaidSummary);
            fSetLabelText(interestWaivedLabel, interestWaivedSummary);
            fSetLabelText(interestWrittenOffLabel, interestWrittenOffSummary);
            fSetLabelText(interestOutstandingLabel, interestOutstandingSummary);
            fSetLabelText(interestOverDueLabel, interestOverDueSummary);
            #endregion
            #region Fees
            fSetLabelText(feesOriginalLabel, feesOriginalSummary);
            fSetLabelText(feesPaidLabel, feesPaidSummary);
            fSetLabelText(feesPaidLabel, feesPaidSummary);
            fSetLabelText(feesWaivedLabel, feesWaivedSummary);
            fSetLabelText(feesWrittenOffLabel, feesWrittenOffSummary);
            fSetLabelText(feesOutstandingLabel, feesOutstandingSummary);
            fSetLabelText(feesOverDueLabel, feesOverDueSummary);
            #endregion
            #region Penalties
            fSetLabelText(penaltiesOriginalLabel, penaltiesOriginalSummary);
            fSetLabelText(penaltiesPaidLabel, penaltiesPaidSummary);
            fSetLabelText(penaltiesWaivedLabel, penaltiesWaivedSummary);
            fSetLabelText(penaltiesWrittenOffLabel, penaltiesWrittenOffSummary);
            fSetLabelText(penaltiesOutstandingLabel, penaltiesOutstandingSummary);
            fSetLabelText(penaltiesOverDueLabel, penaltiesOverDueSummary);
            #endregion
            #region Total
            totalOriginalSummary = principalOriginalSummary + interestOriginalSummary + feesOriginalSummary + penaltiesOriginalSummary;
            fSetLabelText(totalOriginalLabel, totalOriginalSummary);

            totalPaidSummary = principalPaidSummary + interestPaidSummary + feesPaidSummary + penaltiesPaidSummary;
            fSetLabelText(totalPaidLabel, totalPaidSummary);

            totalWaivedSummary = principalWaivedSummary + interestWaivedSummary + feesWaivedSummary + penaltiesWaivedSummary;
            fSetLabelText(totalWaivedLabel, totalWaivedSummary);

            totalWrittenOffSummary = principalWrittenOffSummary + interestWrittenOffSummary + feesWrittenOffSummary + penaltiesWrittenOffSummary;
            fSetLabelText(totalWrittenOffLabel, totalWrittenOffSummary);

            totalOutstandingSummary = principalOutstandingSummary + interestOutstandingSummary + feesOutstandingSummary + penaltiesOutstandingSummary;
            fSetLabelText(totalOutstandingLabel, totalOutstandingSummary);

            totalOverDueSummary = principalOverDueSummary + interestOverDueSummary + feesOverDueSummary + penaltiesOverDueSummary;
            fSetLabelText(totalOverDueLabel, totalOverDueSummary);
            #endregion
        }
    }

    private void fSetLabelText(Label resultLabel, decimal decimalValue)
    {
        resultLabel.Text = string.Format("{0:0.00}", decimalValue);
    }

    private void FillAccountDetail(int loanID)
    {
        DataTable sourceDT = new DataTable();
        try
        {
            sourceDT = Utils.ModuleMain().GetAccountDetail(loanID);
            if (sourceDT != null && sourceDT.Rows.Count == 1)
            {
                repaymentStrategyLabel.Text = sourceDT.Rows[0]["Repayment Strategy"].ToString();
                repaymentsLabel.Text = sourceDT.Rows[0]["Repayments"].ToString();
                amortizationLabel.Text = sourceDT.Rows[0]["Amortization"].ToString();
                interestLabel.Text = sourceDT.Rows[0]["Amortization"].ToString();
                gracePrincipalLabel.Text = sourceDT.Rows[0]["Grace Principal Payment"].ToString();
                graceInterestLabel.Text = sourceDT.Rows[0]["Grace Interest Payment"].ToString();
                graceArrearsLabel.Text = sourceDT.Rows[0]["Grace Arrears Ageing"].ToString();
                fundSourceLabel.Text = sourceDT.Rows[0]["Fund Source"].ToString();
                interestFreePeriodLabel.Text = sourceDT.Rows[0]["Interest Free Period"].ToString();
                interestCalculationPeriodLabel.Text = sourceDT.Rows[0]["Interest Calculation Period"].ToString();
                interestTypeLabel.Text = sourceDT.Rows[0]["Interest Type"].ToString();
                submittedOnLabel.Text = sourceDT.Rows[0]["Submitted"].ToString();
                approvedOnLabel.Text = sourceDT.Rows[0]["Approved"].ToString();
                disbursedOnLabel.Text = sourceDT.Rows[0]["Disbursed"].ToString();
                matureseOnLabel.Text = sourceDT.Rows[0]["Matures"].ToString();
            }
        }
        catch (Exception ex)
        {
            //todo
        }
    }

    protected void ClearPreviewForm()
    {
        dateNowLabel.Text = string.Empty;
        clientNameLabel.Text = string.Empty;
        loanNrLabel.Text = string.Empty;
        loanInitialChangeRateLabel.Text = string.Empty;
        loanRealChangeRate.Text = string.Empty;

        //refundsLoanGridView.DataSource = null;
        //refundsLoanGridView.DataBind();

        refundGridView.DataSource = null;
        refundGridView.DataBind();

        tranzactionGridView.DataSource = null;
        tranzactionGridView.DataBind();
    }

    protected void FillPreviewForm(int loanID)
    {
        try
        {
            ClearPreviewForm();
            dateNowLabel.Text = DateTime.Now.ToString(Constants.Constants.ISODateBackwardDotsFormat);

            if (loanID != 0)
            {
                Credits.DataObjects.LoanObject loanInfo = Utils.ModuleCredits().GetLoanObjectByID(loanID);
                if (loanInfo != null)
                {
                    clientNameLabelID.Text = loanInfo.ClientFirstLastName;
                    loanLabelID.Text = loanInfo.ContractCode.ToString();

                    clientNameLabel.Text = loanInfo.ClientFirstLastName;
                    loanNrLabel.Text = loanInfo.ContractCode.ToString();
                    //sumLoanLabel.Text = loanInfo.ContractAmountInLei.ToString(specifier);                    
                    changeRateHiddenField.Value = loanInfo.CurrencyID.ToString();

                    decimal sumLoan = 0;
                    decimal percentLoan = 0;
                    decimal.TryParse(loanInfo.ContractAmountInLei.ToString(), out sumLoan);
                    decimal.TryParse(loanInfo.ContrcatPercent.ToString(), out percentLoan);
                    percentLoan = percentLoan / 100;
                    //interestLoanLabel.Text = (sumLoan * percentLoan).ToString(specifier);

                    //totalLoanLabel.Text = (sumLoan + (sumLoan * percentLoan)).ToString(specifier);

                    if (loanInfo.CurrencyID != 0 && loanInfo.CurrencyID != (int)Constants.Constants.CurrencyList.MDL)
                    {
                        decimal initialChangeRate = loanInfo.CurrencyChangeRate;
                        decimal realChangeRate = Utils.ModuleCredits().GetCurrencyRateByDate(DateTime.Now.Date, loanInfo.CurrencyID);

                        string currencyChange = loanInfo.CurrencyChangeRate.ToString();
                        if (string.IsNullOrEmpty(currencyChange))
                        {
                            currencyChange = "1";
                        }
                        loanInitialChangeRateLabel.Text = currencyChange;

                        loanRealChangeRate.Text = realChangeRate.ToString();

                        if (initialChangeRate < realChangeRate)
                        {
                            Utils.ModuleCredits().ApplyNewChangeRateForloanOrders(loanID, realChangeRate, DateTime.Now.Date);
                        }
                    }
                    else
                    {
                        string currencyChange = loanInfo.CurrencyChangeRate.ToString();
                        if (string.IsNullOrEmpty(currencyChange))
                        {
                            currencyChange = "1";
                        }
                        loanInitialChangeRateLabel.Text = currencyChange;
                    }


                }
            }
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    #region initierea variabilelor
    decimal sumRateAmountForFooter = 0;
    decimal sumRatePaysForFooter = 0;
    decimal sumRateDiffForFooter = 0;

    decimal sumPercentAmountForFooter = 0;
    decimal sumPercentPaysForFooter = 0;
    decimal sumPercentDiffForFooter = 0;

    decimal sumPenaltyForFooter = 0;
    decimal sumPenaltyPaysForFooter = 0;
    decimal sumPenaltyDiffForFooter = 0;

    decimal sumCorrentionAmountForFooter = 0;
    decimal sumCorrectionPaysForFooter = 0;
    decimal sumCorrectionDiffForFooter = 0;

    decimal sumCommissionForFooter = 0;
    decimal sumCommissionPaysForFooter = 0;
    decimal sumCommissionDiffForFooter = 0;

    decimal sumTotalAmountForFooter = 0;
    decimal sumTotalPaysForFooter = 0;
    decimal sumTotalDiffForFooter = 0;

    #endregion

    DateTime curretDate = DateTime.Now;

    protected void RefundsSelecetd_Event(object sender, Controls_LoanRepayment.RefundsWindowEventsArg e)
    {
        //ShowPanel(previewPanel.ID);
    }

    protected void FillStartUP(int loanID)
    {
        DataTable sourceDT = new DataTable();
        sourceDT = Utils.ModuleMain().GetStartUP(loanID);
        if (sourceDT != null && sourceDT.Rows.Count == 1)
        {
            
            disbursementDateLabel.Text = sourceDT.Rows[0]["DisbursementDate"].ToString();
            loanPurposeLabel.Text = sourceDT.Rows[0]["LoanPurpose"].ToString();
            approvedAmountLabel.Text = sourceDT.Rows[0]["ApprovedAmount"].ToString();
            loanOfficerLabel.Text = sourceDT.Rows[0]["LoanOfficer"].ToString();
            disburseAmountLabel.Text = sourceDT.Rows[0]["DisburseAmount"].ToString();
            arrearsByLabel.Text = sourceDT.Rows[0]["ArrearsBy"].ToString();
        }
        Credits.DataObjects.LoanObject loanInfo = Utils.ModuleCredits().GetLoanObjectByID(loanID);
        if (loanInfo != null)
        {
            currencyLabel.Text = loanInfo.CurrencyChangeRate.ToString(); //sourceDT.Rows[0]["Currency"].ToString();
        }
    }

    #region makeRepayment

    protected void ClearPersonalDataForms(int loanID)
    {
        editPayIDHiddenFieldID.Value = string.Empty;
        transactionDateTextBox.Text = string.Empty;
        transactionAmounTextBox.Text = string.Empty;

        FillStartUP(loanID);

        FillAccountDetail(loanID);
        FillPreviewForm(loanID);

        FillRepaymentSchedule(loanID);
        FillTransaction(loanID);
        FillLoanDocuments(loanID);
    }

    protected void saveButton_Click(object sender, EventArgs e)
    {
        try
        {
            if (transactionAmounTextBox.Text.Equals(string.Empty) || transactionDateTextBox.Text.Equals(string.Empty))
            {
                Utils.InfoText(this, "Atentie! Eroare in sistem!", "Introduceti data si suma achitata");
            }
            else
            {
                int parentID = 0;

                int mLoanID = 0;
                int.TryParse(Request["loanID"], out mLoanID);

                DateTime payDate = Convert.ToDateTime(transactionDateTextBox.Text);

                #region select max tranzaction date
                bool isLastDate = true;
                DataTable tranzactionDT = Utils.ModuleCredits().GetTranzactionsLoanOrderDT(mLoanID);
                if (tranzactionDT != null && tranzactionDT.Rows.Count > 0)
                {
                    DateTime maxDateTranzaction = (DateTime)tranzactionDT.Rows[0]["TranzactionDate"];
                    decimal delayDaysCount = (decimal)((payDate - maxDateTranzaction).TotalDays);
                    if (delayDaysCount < 0)
                    {
                        isLastDate = false;
                    }
                }

                #endregion

                decimal inputCurent = 0;
                decimal.TryParse(transactionAmounTextBox.Text.Replace('.', ','), out inputCurent);
                if (inputCurent > 0)
                {
                    bool isPenalty = false;
                    isPenalty = isPenalitateCheckBoxID.Checked;

                    if (editPayIDHiddenFieldID.Value.Equals(string.Empty))
                    {
                        if (isLastDate)
                        {                            
                            AddRefund(mLoanID, inputCurent, payDate, parentID, isPenalty);
                        }
                        else
                        {
                            //data tranzactiei curente este mai mica ca ultima data a tranzactiilor
                            // 1. cream tabel cu toate achitarile, le sortam dupa payDate
                            // 2. stergem din baza toate tranzactiile pentru loanid
                            // 3. le inseram din nou dupa data.

                            if (tranzactionDT != null && tranzactionDT.Rows.Count > 0)
                            {
                                #region step_1
                                DataRow newRow = tranzactionDT.NewRow();

                                newRow["TranzactionID"] = 0;
                                newRow["TranzactionsOffice"] = string.Empty;
                                newRow["TranzactionDate"] = payDate;
                                newRow["Type"] = string.Empty;
                                newRow["Amount"] = inputCurent;
                                newRow["Principal"] = 0;
                                newRow["Interest"] = 0;
                                newRow["Fees"] = 0;
                                newRow["Penalties"] = 0;
                                newRow["isPenalty"] = isPenalty;

                                tranzactionDT.Rows.InsertAt(newRow, tranzactionDT.Rows.Count);

                                #endregion

                                UpdateLastTranzaction(tranzactionDT, mLoanID);
                            }
                        }
                    }
                    else
                    {
                        int payID = int.Parse(editPayIDHiddenFieldID.Value);
                        bool result = DeleteTranzaction(payID);
                        if (result)
                        {
                            DataTable tranzactDT = Utils.ModuleCredits().GetTranzactionsLoanOrderDT(mLoanID);
                            if (tranzactDT != null && tranzactDT.Rows.Count > 0)
                            {
                                DataRow newRow = tranzactDT.NewRow();

                                newRow["TranzactionID"] = 0;
                                newRow["TranzactionsOffice"] = string.Empty;
                                newRow["TranzactionDate"] = payDate;
                                newRow["Type"] = string.Empty;
                                newRow["Amount"] = inputCurent;
                                newRow["Principal"] = 0;
                                newRow["Interest"] = 0;
                                newRow["Fees"] = 0;
                                newRow["Penalties"] = 0;
                                newRow["isPenalty"] = isPenalty;

                                tranzactDT.Rows.InsertAt(newRow, tranzactDT.Rows.Count);
                            }
                            UpdateLastTranzaction(tranzactDT, mLoanID);
                        }
                    }

                    ClearPersonalDataForms(mLoanID);
                }
                else
                {
                    Utils.InfoText(this, "Atentie! Eroare in sistem!", "Suma trebuie sa fie mai mare ca 0(zero)");
                }
            }
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    private void UpdateLastTranzaction(DataTable tranzactionDT, int mLoanID)
    {
        try
        {
            if (tranzactionDT != null && tranzactionDT.Rows.Count > 0)
            {
                tranzactionDT.DefaultView.Sort = string.Format("TranzactionDate ASC");
                tranzactionDT = tranzactionDT.DefaultView.ToTable();

                for (int index = 0; index < tranzactionDT.Rows.Count; index++)
                {
                    string tranzactionValue = tranzactionDT.Rows[index]["TranzactionID"].ToString();
                    int tranzactionID = 0;
                    int.TryParse(tranzactionValue, out tranzactionID);

                    if (tranzactionID != 0)
                    {
                        bool resultDelete = Utils.ModuleCredits().DeleteRefundByPayID(tranzactionID);
                        if (resultDelete)
                        {
                            bool resultUpdate = Utils.ModuleCredits().UpdateFinishedTrancheByLoanID(mLoanID);
                        }
                    }
                }

                for (int index = 0; index < tranzactionDT.Rows.Count; index++)
                {
                    int parentID = 0;
                    decimal amount = 0;
                    decimal.TryParse(tranzactionDT.Rows[index]["Amount"].ToString(), out amount);
                    if (amount > 0)
                    {
                        DateTime tranzactionDate = (DateTime)tranzactionDT.Rows[index]["TranzactionDate"];
                        bool isPenalty = false;
                        bool.TryParse(tranzactionDT.Rows[index]["isPenalty"].ToString(), out isPenalty);

                        AddRefund(mLoanID, amount, tranzactionDate, parentID, isPenalty);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! eroare in sistem!", ex.Message);
        }
    }

    private void AddRefund(int mLoanID, decimal inputCurent, DateTime payDate, int parentID, bool isPenalty)
    {
        try
        {
            Credits.DataObjects.LoanObject loanInfo = Utils.ModuleCredits().GetLoanObjectByID(mLoanID);

            DataTable sessionDataTable = Utils.ModuleCredits().GetRefundsLoanOrderDT1(mLoanID);

            if (sessionDataTable != null && sessionDataTable.Rows.Count > 0)
            {
                sessionDataTable.Rows.RemoveAt(0);
                sessionDataTable.Rows.RemoveAt(sessionDataTable.Rows.Count - 1);
                DataRow[] selectRows = sessionDataTable.Select("outstandingID > 0");
                if (selectRows != null && selectRows.Length > 0)
                {
                    int minIndexRow = 0;

                    int minIterationSelect = 0;
                    int.TryParse(selectRows[0]["iterationID"].ToString(), out minIterationSelect);

                    for (int indexRow = 0; indexRow < selectRows.Length; indexRow++)
                    {
                        string sIterationValue = selectRows[indexRow]["iterationID"].ToString();
                        int sIterationID = 0;
                        int.TryParse(sIterationValue, out sIterationID);

                        if (sIterationID < minIterationSelect)
                        {
                            minIterationSelect = sIterationID;
                            minIndexRow = indexRow;
                        }
                    }

                    //string iterationValue = selectRows[0]["iterationID"].ToString();
                    //int iterationID = 0;
                    //int.TryParse(iterationValue, out iterationID);
                    //int minIterationID = iterationID - 1;
                    int minIterationID = minIterationSelect - 1;

                    DateTime dateGrafic = (DateTime)selectRows[minIndexRow]["DateID"];

                    decimal delayDaysCount = (decimal)((payDate - dateGrafic).TotalDays);

                    string profitGraficValue = selectRows[minIndexRow]["interestID"].ToString();
                    decimal profitGrafic = 0;
                    decimal.TryParse(profitGraficValue, out profitGrafic);

                    //decimal profitCumulativ = profitGrafic;

                    decimal cursValue = 1;
                    //profitGrafic = profitGrafic * cursValue;

                    string mainGraficValue = selectRows[minIndexRow]["principalDueID"].ToString();
                    decimal mainGrafic = 0;
                    decimal.TryParse(mainGraficValue, out mainGrafic);
                    //mainGrafic = mainGrafic * cursValue;

                    string outstandingValue = selectRows[minIndexRow]["outstandingID"].ToString();
                    decimal outstanding = 0;
                    decimal.TryParse(outstandingValue, out outstanding);

                    decimal penalitateCurent = 0;
                    decimal lateCurent = 0;

                    decimal avansValue = 0;

                    decimal profitCurent = 0;
                    decimal mainCurent = 0;
                    decimal difInput = inputCurent;

                    decimal minQP = 0;

                    //D0 = if(Q-M<0,0,Q-M)
                    //minQP = min(Q,P)
                    //R1 = if(minQP-D0<0,0,minQP-D0)
                    //D1 = minQP - R1

                    if (delayDaysCount > 0)
                    {
                        if (isPenalitateCheckBoxID.Checked)
                        {
                            if (loanInfo != null)
                            {
                                decimal penaltyRate = loanInfo.ContractPenalty;
                                penalitateCurent = (((profitGrafic + mainGrafic) * penaltyRate) / 100) * delayDaysCount;
                                if (penalitateCurent > inputCurent) { penalitateCurent = inputCurent; }
                            }
                        }
                        difInput = inputCurent - penalitateCurent;
                        if (outstanding - difInput > 0) { lateCurent = outstanding - difInput; }
                    }

                    if (difInput - outstanding > 0) { avansValue = difInput - outstanding; }

                    decimal profitPrecedent = 0;
                    if (outstanding - mainGrafic < 0) { profitPrecedent = 0; }
                    else { profitPrecedent = outstanding - mainGrafic; }

                    minQP = Math.Min(outstanding, difInput);

                    if (minQP - profitPrecedent < 0) { mainCurent = 0; }
                    else { mainCurent = minQP - profitPrecedent; }

                    profitCurent = minQP - mainCurent;

                    decimal penalty = penalitateCurent;

                    decimal commission = 0;
                    decimal lateValuta = 0;
                    #region calc commission
                    if (loanInfo != null)
                    {
                        decimal currencyChange = loanInfo.CurrencyChangeRate;
                        decimal realChangeRate = Utils.ModuleCredits().GetCurrencyRateByDate(payDate, loanInfo.CurrencyID);
                        if (currencyChange != null && realChangeRate != null)
                        {
                            if (realChangeRate - currencyChange > 0 && currencyChange!=0)
                            {
                                //commission = ((mainCurent + profitCurent) / currencyChange) * realChangeRate - (mainCurent + profitCurent);
                                decimal sumGraficValuta = (profitGrafic + mainGrafic)/currencyChange;
                                decimal sumGraficLei = sumGraficValuta * realChangeRate;
                                decimal difGraficLei = 0;
                                if (sumGraficLei > (profitGrafic+mainGrafic))
                                {
                                    difGraficLei = sumGraficLei - (profitGrafic + mainGrafic);
                                }
                                
                                commission = (difGraficLei * inputCurent) / sumGraficLei;
                                decimal sumCurent = inputCurent - commission;
                                lateValuta = (sumGraficLei - inputCurent)/realChangeRate;
                            }
                        }
                    }
                    #endregion calc_commission

                    if (commission != 0)
                    {
                        decimal difAmmount = mainCurent + profitCurent;
                        decimal restAmmount = difAmmount - commission;

                        if (restAmmount - profitCurent < 0)
                        {
                            mainCurent = 0;
                        }
                        else
                        {
                            mainCurent = restAmmount - profitCurent;
                        }

                        profitCurent = restAmmount - mainCurent;
                    }

                    int newPayID = 0;

                    bool result = Utils.ModuleCredits().AddNewRefund(mLoanID
                        , minIterationID
                        , payDate
                        , mainCurent
                        , profitCurent
                        , penalitateCurent
                        , cursValue
                        , commission
                        , avansValue
                        , lateCurent
                        , parentID
                        , isPenalty
                        , lateValuta
                        , out newPayID);

                    bool resultFinishedTranche = Utils.ModuleCredits().UpdateFinishedTrancheByLoanID(mLoanID);

                    if (avansValue > 0)
                    {
                        if (parentID == 0) parentID = newPayID;
                        AddRefund(mLoanID, avansValue, payDate, parentID, isPenalty);
                    }
                }

                Utils.ModuleCredits().MarkLoanAsFinishedIfAllTransheFinished(loanInfo);
            }
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! eroare in sistem!", ex.Message);
        }
    }

    protected void cancelButton_Click(object sender, EventArgs e)
    {
        int mLoanID = 0;
        int.TryParse(Request["loanID"], out mLoanID);
        ClearPersonalDataForms(mLoanID);
    }

    protected void tranzactionGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int index = e.RowIndex;
            string payValue = tranzactionGridView.Rows[index].Cells[0].Text;
            int payID = -1;
            int.TryParse(payValue, out payID);

            bool result = DeleteTranzaction(payID);

            if (result)
            {
                int mLoanID = 0;
                int.TryParse(Request["loanID"], out mLoanID);

                FillTransaction(mLoanID);
                FillRepaymentSchedule(mLoanID);
            }
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! eroare in sistem!", ex.Message);
        }

    }

    private bool DeleteTranzaction(int payID)
    {
        bool resultDelete = Utils.ModuleCredits().DeleteRefundByPayID(payID);
        if (resultDelete)
        {
            int mLoanID = 0;
            int.TryParse(Request["loanID"], out mLoanID);

            DataTable tranzactionDT = Utils.ModuleCredits().GetTranzactionsLoanOrderDT(mLoanID);

            UpdateLastTranzaction(tranzactionDT, mLoanID);
        }
        return resultDelete;
    }

    protected void tranzactionGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            int index = e.NewEditIndex;

            editPayIDHiddenFieldID.Value = tranzactionGridView.Rows[index].Cells[0].Text;

            int mLoanID = 0;
            int.TryParse(Request["loanID"], out mLoanID);

            decimal inputCurent = 0;
            DateTime payDate = new DateTime();

            bool isPenalitate = true;

            DataTable tranzactionDT = Utils.ModuleCredits().GetTranzactionsLoanOrderDT(mLoanID);
            if (tranzactionDT != null && tranzactionDT.Rows.Count > 0)
            {
                DataRow[] selectedRow = tranzactionDT.Select("TranzactionID = " + editPayIDHiddenFieldID.Value);

                if (selectedRow != null && selectedRow.Length > 0)
                {
                    string amount = selectedRow[0]["Amount"].ToString();

                    decimal.TryParse(amount, out inputCurent);

                    string dateValue = selectedRow[0]["TranzactionDate"].ToString();
                    payDate = Convert.ToDateTime(dateValue);

                    decimal penalitate = 0;
                    string penalitateValue = selectedRow[0]["Penalties"].ToString();
                    decimal.TryParse(penalitateValue, out penalitate);
                    if (penalitate == 0)
                    {
                        isPenalitate = false;
                    }
                }
            }
            transactionAmounTextBox.Text = string.Format("{0:0.00}", inputCurent.ToString().Replace('.', ','));
            transactionDateTextBox.Text = string.Format("{0:dd.MM.yyyy}", payDate);
            isPenalitateCheckBoxID.Checked = isPenalitate;
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    #endregion makeRepayment

}